import java.util.Scanner;

public class Test {
    static class Node{
        public int val;
        public Node next;

        public Node(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {

    }

    public int LastRemaining_Solution (int n, int m) {
        // write code here
        Node prev = createCycle(n);
        Node cur = prev.next;
        int count = 1;
        while (prev != cur){
            if(count < m){
                cur = cur.next;
                prev = prev.next;
                count++;
            }else {
                prev.next = cur.next;
                cur = cur.next;
                count = 1;
            }
        }
        return cur.val;
    }

    public   Node createCycle(int n){
        Node begin = new Node(0);
        Node node = begin;
        for (int i = 1; i < n; i++) {
            Node cur = new Node(i);
            node.next = cur;
            node = node.next;
        }
        node.next = begin;
        return node;
    }
}

